<template>
  <div ref="dialogModal">
    <!-- :overlay-style="{ zIndex: 1999 }"
        style="z-index: 2000 !important" -->
    <van-dialog
      v-model="modalShow"
      :title="title"
      show-cancel-button
      confirm-button-color="#548af1"
      :before-close="beforeClose"
      :lazy-render="true"
    >
      <div class="modal-container">
        <el-form
          :model="formData"
          :rules="typeRules"
          label-width="8em"
          style="width: 100%"
          ref="modalForm"
        >
          <el-form-item required label="编码规则类型" prop="type">
            <el-select
              v-model="formData.type"
              @change="changeRulesType"
              style="z-index: 20010 !important"
              popper-class="zIndex"
            >
              <el-option
                v-for="(item, index) in codingRulesTypeList"
                :key="index"
                :label="setRuleLabel(item.prefixDetail)"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-for="(item, index) in ruleFormItems"
            :key="index"
            :label="item.name"
            :prop="`prefix${index}`"
            :rules="
              item.type === 1
                ? [
                    {
                      required: true,
                      message: '该参数是必填项',
                      trigger: ['blur', 'change'],
                    },
                  ]
                : []
            "
          >
            <!-- type 为 1 是人工输入-->
            <el-input
              v-model="formData[`prefix${index}`]"
              placeholder="请输入内容"
              clearable
              :disabled="item.type !== 1"
            />
          </el-form-item>
          <!-- <el-form-item label="固定信息">
              <el-input disabled v-model="formData.example"></el-input>
            </el-form-item>
            <el-form-item label="当前日期">
              <el-input disabled v-model="formData.example"></el-input>
            </el-form-item>
            <el-form-item label="自动生成序号">
              <el-input disabled v-model="formData.example"></el-input>
            </el-form-item> -->
          <el-form-item label-width="1em">
            <span style="color: red">样例：{{ example }}</span>
          </el-form-item>
        </el-form>
      </div>
    </van-dialog>
  </div>
</template>
  
  <script>
import { getNumRuleDetailByType, getNumRuleSeqByType } from "@/api/inventory";
export default {
  data() {
    return {
      formData: {
        type: "",
        orderNo: "",
      },
      codingRulesTypeList: [],
      typeRules: {
        type: [
          {
            required: true,
            message: "请先选择规则类型",
            trigger: ["change"],
          },
        ],
      },
      readonly: false,
      ruleFormItems: [],
    };
  },
  props: {
    value: {
      type: String,
      default: "",
    },
    show: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "订单编号",
    },
  },
  computed: {
    modalShow: {
      get() {
        return this.show;
      },
      set() {
        this.$emit("update:show", !this.show);
      },
    },
    example() {
      const keys = Object.keys(this.formData);
      let str = "";
      keys.forEach((i) => {
        if (i !== "type") {
          str += this.formData[i];
        }
      });
      // this.$emit('update:value',str)
      return str;
    },
    // example: {
    //   get() {
    //     const keys = Object.keys(this.formData);
    //     let str = "";
    //     console.log(keys)
    //     keys.forEach((i) => {
    //       if (i !== "type") {
    //         str += this.formData[i];
    //         console.log(str)
    //       }
    //     });
    //     this.$emit('update:value',str)
    //     return str;
    //   },
    //   set(val){
    //     this.$emit('update:value',val)
    //   }
    // },
  },
  created() {
    this.getRuleDialogType();
  },
  methods: {
    beforeClose(action, done) {
      if (action == "confirm") {
        this.$refs.modalForm.validate((valid) => {
          if (valid) {
            done();
            this.$emit("confirm", this.example);
            // this.$emit('update:value',this.example)
          } else {
            done(false);
          }
        });
      } else {
        done();
      }
    },
    async changeRulesType(val, flag) {
      let type = JSON.parse(JSON.stringify(this.formData.type));
      this.formData = {};
      this.formData.type = flag ? val : type;
      const {
        data: {
          code,
          data: { prefixValueList = [] },
          message,
        },
      } = await getNumRuleSeqByType({ id: val });
      if (code === "200") {
        this.ruleFormItems = prefixValueList;
        prefixValueList.forEach((i, index) => {
          this.$set(this.formData, `prefix${index}`, i.value);
        });
        return prefixValueList;
      } else {
        this.$notify({
          title: "提示",
          message: message || "服务异常",
          type: "error",
          duration: 2000,
        });
      }
    },
    // 获取规则列表数据
    async getRuleDialogType() {
      try {
        const param = { typeCode: 35 };
        const res = await getNumRuleDetailByType(param);
        const { code, data = [], message } = res.data || {};
        if (+code === 200) {
          this.codingRulesTypeList = data;
          const len = data.length;
          const defaultData =
            this.codingRulesTypeList.filter((i) => i.isDefault)[0] || null;
          const flag = defaultData ? false : true
          switch (len) {
            case 0:
              this.readonly = false;
              break;
            case 1:
              const prefixValueList = await this.getRuleByType({
                id: this.codingRulesTypeList[0].id,
              });
              const someHasNormal = prefixValueList.filter((i) => i.type === 1);
              if (someHasNormal.length === 0) {
                // 无人工输入时直接生成编码规则
                this.formData.orderNo = prefixValueList.reduce((sum, item) => {
                  return sum + item.value;
                }, "");
                this.$emit("confirm", this.formData.orderNo);
              } else if (someHasNormal.length === prefixValueList.length) {
                // 全是人工输入的情况 直接不弹框允许手动输入
                this.readonly = false;
                break;
              } else {
                // 存在人工输入和其他信息时
                  const currentFormData = JSON.parse(sessionStorage.getItem('currentFormData')) || {}
                if(currentFormData.orderNumber){
                  this.$emit("update:show", false);
                }else{
                  this.$emit("update:show", flag);
                }
              }
              break;
            default:
                console.log(flag)
                const currentFormData = JSON.parse(sessionStorage.getItem('currentFormData')) || {}
                if(currentFormData.orderNumber){
                  this.$emit("update:show", false);
                }else{
                  this.$emit("update:show", flag);
                }
              
          }
          if (!defaultData) {
            return;
          }
          await this.changeRulesType(defaultData.id, true)
          this.$emit("confirm", this.example);
        } else {
          this.$notify({
            title: "提示",
            message: message || "获取规则详情失败",
            type: "error",
            duration: 2000,
          });
        }
      } catch (err) {
        this.codingRulesTypeList = [];
      }
    },
    // 订单编号获取规则
    async getRuleByType(value) {
      const res = await getNumRuleSeqByType(value);
      const { code, data, message } = res.data || {};
      if (+code === 200) {
        const { prefixValueList } = data || {};
        return prefixValueList;
      } else {
        this.$notify({
          title: "提示",
          message: message || "选择类型失败",
          type: "error",
          duration: 2000,
        });
      }
    },
    setRuleLabel(prefixDetail) {
      const nPrefixDetail = JSON.parse(prefixDetail || "[]");
      const str = nPrefixDetail.reduce((str, i) => {
        str = str + i.name + "-";
        return str;
      }, "");
      return str.slice(0, -1);
    },
  },
};
</script>
  
  <style lang="scss" scoped>
@dialog-border-radius: 5px;
/deep/ .modal-container {
  background-color: #ffffff;
  border-radius: 1px;
  padding: 10px 15px;
  z-index: 2000;
}
.van-dialog {
  border-radius: 5px;
}
/deep/ .zIndex {
  z-index: 2010 !important;
}
</style>
  <style >
.el-select-dropdown {
  z-index: 20010 !important;
}
</style>